<template>
  <div class="forgot-password-container flex justify-center items-center min-h-screen bg-light-bg-primary dark:bg-dark-bg-primary blue:bg-blue-bg-primary transition-colors duration-300">
    <div class="forgot-password-form-wrapper w-full max-w-md px-4 py-8 bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary rounded-lg shadow-lg border border-light-border dark:border-dark-border blue:border-blue-border">
      <div class="forgot-password-header text-center mb-6">
        <h2 class="text-2xl font-bold text-accent-color mb-2">新易访内网系统</h2>
        <p class="text-light-text-secondary dark:text-dark-text-secondary blue:text-blue-text-secondary">找回您的密码</p>
      </div>
      
      <el-form 
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
        ref="forgotPasswordFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="forgotPasswordForm.username"
            placeholder="请输入您的用户名"
            prefix-icon="User"
            class="bg-light-bg-primary dark:bg-dark-bg-primary blue:bg-blue-bg-primary text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary"
          />
        </el-form-item>
        
        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-code-wrapper flex gap-3">
            <el-input
              v-model="forgotPasswordForm.verificationCode"
              placeholder="请输入验证码"
              prefix-icon="Message"
              class="flex-1 bg-light-bg-primary dark:bg-dark-bg-primary blue:bg-blue-bg-primary text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary"
            />
            <el-button
              type="primary"
              :disabled="countingDown"
              @click="sendVerificationCode"
              class="send-code-btn bg-accent-color hover:bg-accent-color/90"
            >
              {{ countingDown ? `${countdown}秒后重新发送` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="forgotPasswordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            prefix-icon="Lock"
            show-password
            class="bg-light-bg-primary dark:bg-dark-bg-primary blue:bg-blue-bg-primary text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary"
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="forgotPasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            prefix-icon="Lock"
            show-password
            class="bg-light-bg-primary dark:bg-dark-bg-primary blue:bg-blue-bg-primary text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleResetPassword"
            class="reset-password-btn w-full h-10 text-base bg-accent-color hover:bg-accent-color/90"
          >
            {{ loading ? '处理中...' : '重置密码' }}
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <div class="login-link text-center mt-4">
            <router-link to="/login" class="text-accent-color hover:underline transition-all">返回登录</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onUnmounted } from 'vue'
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus'
import request from '../../utils/request'
import router from '../../router'
import axios from 'axios'
import { useThemeStore } from '../../stores/theme'

// 初始化主题
const themeStore = useThemeStore()
themeStore.initTheme()

// 表单引用
const forgotPasswordFormRef = ref()

// 加载状态
const loading = ref(false)

// 验证码发送状态
const countingDown = ref(false)
const countdown = ref(60)
let countdownTimer: number | null = null

// 类型定义
interface ForgotPasswordForm {
  username: string;
  verificationCode: string;
  newPassword: string;
  confirmPassword: string;
}

// 表单数据
const forgotPasswordForm = reactive<ForgotPasswordForm>({
  username: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 状态
const sendingCode = ref(false)

// 表单验证规则
const forgotPasswordRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度应在4到6个字符之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: any) => {
        if (value !== forgotPasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!forgotPasswordForm.username) {
    ElMessage.warning('请输入用户名')
    return
  }

  try {
    sendingCode.value = true
    
    // 调用后端发送验证码接口
    await request.post('/api/auth/send-verification-code', {
      username: forgotPasswordForm.username
    })

    ElMessage.success('验证码已发送到您的邮箱，请查收')
    startCountdown() // 开始倒计时
  } catch (error: any) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}


// 开始倒计时
const startCountdown = () => {
  countingDown.value = true
  countdown.value = 60
  
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
  
  countdownTimer = window.setInterval(() => {
    countdown.value--
    
    if (countdown.value <= 0) {
      countingDown.value = false
      if (countdownTimer) {
        clearInterval(countdownTimer)
        countdownTimer = null
      }
    }
  }, 1000)
}

// 处理重置密码
const handleResetPassword = async () => {
  try {
    // 表单验证
    await forgotPasswordFormRef.value?.validate()
    
    // 设置加载状态
    loading.value = true
    
    // 调用重置密码接口
    await axios.post('/api/auth/reset-password', {
      username: forgotPasswordForm.username,
      verificationCode: forgotPasswordForm.verificationCode,
      newPassword: forgotPasswordForm.newPassword
    })
    
    ElMessage.success('密码重置成功，请使用新密码登录')
    router.push('/login')
  } catch (error) {
    ElMessage.error('密码重置失败，请稍后重试')
    console.error('Reset password error:', error)
  } finally {
    loading.value = false
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
/* 确保组件内所有元素都有过渡效果 */
* {
  transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 300ms;
}

/* 覆盖Element Plus的一些样式以支持主题切换 */
:deep(.el-input__inner) {
  background-color: var(--input-bg-color) !important;
  color: var(--input-text-color) !important;
  border-color: var(--border-color) !important;
}

:deep(.el-input__inner:focus) {
  border-color: var(--accent-color) !important;
  box-shadow: 0 0 0 2px var(--accent-color-light) !important;
}

:deep(.el-button--primary) {
  background-color: var(--accent-color) !important;
  border-color: var(--accent-color) !important;
}

:deep(.el-button--primary:hover) {
  background-color: var(--accent-color-hover) !important;
  border-color: var(--accent-color-hover) !important;
}

:deep(.el-form-item__label) {
  color: var(--text-primary) !important;
}

:deep(.el-input__prefix) {
  color: var(--text-secondary) !important;
}

:deep(.el-input__clear) {
  color: var(--text-secondary) !important;
}

:deep(.el-input__password) {
  color: var(--text-primary) !important;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .verification-code-wrapper {
    flex-direction: column !important;
  }
  
  .send-code-btn {
    width: 100% !important;
  }
}
</style>